function [error] =  equivalentvariation(controls,pi1,w,y1vec,pricesAD,priceimpactAD,gamma,relativesize,penalty,utilitytarget)

%This function is used to compute the equivalent variation  that yields the target utility from the
%regulated economy. 

a=controls(1:2);%asset positions
cv=controls(3);

%add the compensating variation to current wealth
w=w+cv;

pivec=[pi1,1-pi1];

c0=w-sum(pricesAD.*a); %Date 0 consumption

cprime=y1vec+a; %Vector of Date 1 consumption

   
%Compute state prices and portfolio optimality conditions

Lambda=(pivec.* cprime.^-gamma)./(c0^(-gamma));

error=Lambda-pricesAD-(relativesize)*priceimpactAD.*a;


%Enfore Inada condition
if min(cprime) <= 0 || c0 <= 0

error = (1 + penalty) * sqrt(error.^2);
    
end

%Compute utility

if gamma==1
    
    U=log(c0) + pi1*log(cprime(1)) + (1-pi1)*log(cprime(2));
else
    
    U=((c0)^(1-gamma))/(1-gamma) + pi1*((cprime(1))^(1-gamma))/(1-gamma) + (1-pi1)*((cprime(2))^(1-gamma))/(1-gamma);

end

utilitydiff=U-utilitytarget;
error=[error,utilitydiff];


end